package com.gouda.temporary.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gouda.temporary.service.InviteLogService;
import com.gouda.temporary.utils.*;
import com.gouda.temporary.vo.InviteLog;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gouda.temporary.context.HongBaoContext;
import com.gouda.temporary.service.HongBaoSendService;
import com.gouda.temporary.vo.HongbaoSend;

@Controller
public class HongbaoController {

	
	
	@Resource
	private HongBaoSendService hongBaoSendService;

	@Resource
	private InviteLogService inviteLogService;

	private static final Logger log = LoggerFactory.getLogger(HongbaoSend.class);

	/**
	 * 按照userid cropid status查找
	 * 测试成功
	 */
	@RequestMapping(value = "/temp/selectHongBaoSend.do")
	public ModelAndView selectHongBaoSend(String userId,String corpId,String status){
		 Map<String, Object> map = new HashMap<String, Object>();
		 List<HongbaoSend> hongbao = this.hongBaoSendService.selectHongBaoSend(userId, corpId, status);		 
		 map.put("hongbao", hongbao);
		 return new ModelAndView("hongbaoList", map);	 
	}
	
	
	/**
	 * 按照status更新
	 * 测试通过
	 */
	@RequestMapping(value = "/temp/updateHongBaoSend.do")
	@ResponseBody
	public Map<String, String> updateHongBaoSend(String userId,String corpId,String status){
		Map<String, String> map = new HashMap<String, String>();
		int rows = this.hongBaoSendService.updateHongBaoSend(userId, corpId, status);
		if(rows>0){
			System.out.println("rows:"+rows);
			map.put("sucess", "更新成功！");
		}else{
			map.put("error", "更新失败！");
		}
		return map;
	}
	/**
	 * 添加方法
	 */
	/*@RequestMapping(value = "/temp/addHongBaoSend.do") @ResponseBody
	public  Map<String,Object> addHongBaoSend(HongbaoSend hongBaoSend,@RequestBody String data) throws JsonParseException, JsonMappingException, IOException{
		System.out.println("addHongBaoSend");
		ObjectMapper mapper = new ObjectMapper(); 
		HongBaoContext context  = mapper.readValue(data, HongBaoContext.class);
		hongBaoSend = new HongbaoSend();
		hongBaoSend.setId(context.getId());
		hongBaoSend.setUserId(context.getUserId());
		hongBaoSend.setCorpId(context.getCorpId());
		hongBaoSend.setCreateTime(context.getCreateTime());
		hongBaoSend.setMoney(context.getMoney());
		hongBaoSend.setStatus(context.getStatus());
		hongBaoSend.setErrormes(context.getErrormes());
		hongBaoSend.setErrorcode(context.getErrorcode());
		hongBaoSend.setIfaccept(context.getIfaccept());
		hongBaoSend.setIsdel(context.getIsdel());
		int rows = this.hongBaoSendService.addHongBaoSend(hongBaoSend);
		Map<String,Object> map = new HashMap<String,Object>();  
		if(rows>0){
			map.put("sucess", "成功！");
		}else{
			map.put("error", "失败！");
		}
		return map;
	}*/


	@RequestMapping(value = "/temp/huidiao")
	public void huidiao(HttpServletRequest request,HttpServletResponse response) throws IOException {
		//这个Token是随机生成，但是必须跟企业号上的相同  //多企业号时此参数必须配置相同
		String sToken = "VT2nOnlZC9V15Bst9BbaEXq0Jd";
		//String Secret ="z0WPKwOselr_A0EYFaVGTVOSpsA1iIsW493_WhT9cfHdxM0ufyv6bBHYMkVlt6Me";
		//这个EncodingAESKey是随机生成，但是必须跟企业号上的相同
		/**      * 确认请求来自微信服务器      * @throws IOException       */
		//多企业号时此参数必须配置相同
		String sEncodingAESKey = "JgrQJqWOL0UBjIyoc1tJ8V1XxdA2MQjj7BzDQ4QjavI";
		// 这里是你企业号的CorpID
		String sCorpID = "wx6a3274ac5b596aea";
		// 微信加密签名
		String sVerifyMsgSig =  request.getParameter("msg_signature");
		// 时间戳
		String sVerifyTimeStamp = request.getParameter("timestamp");
		// 随机数
		String sVerifyNonce = request.getParameter("nonce");
		// 随机字符串 开启回调模式时需要将此字符串解密成明文输出详见OwnerController下wuyehongbao
		//String sVerifyEchoStr = request.getParameter("echostr");
		// 需要返回的明文
		log.info("sToken:" + sToken);
		log.info("sCorpID:" + sCorpID);
		log.info("sEncodingAESKey:" + sEncodingAESKey);
		log.info("msg_signature:" + sVerifyMsgSig);
		log.info("timestamp:" + sVerifyTimeStamp);
		log.info("nonce:" + sVerifyNonce);
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while((line = br.readLine())!=null){
			sb.append(line);
		}
		String  mxml=sb.toString();
		log.info("postData:"+mxml);
		String FormUserName="";
		String Event="";
		String[] arr;
		String Encrypt="";
		if(mxml.indexOf("Encrypt")>0)
		{
			arr = mxml.split("Encrypt");
			Encrypt=arr[1].toString();
			Encrypt=rStr(Encrypt);
		}
		if(mxml.indexOf("ToUserName")>0) {
			arr = mxml.split("ToUserName");
			sCorpID=arr[1].toString();
			sCorpID=rStr(sCorpID);
		}
		System.out.println("Encrypt:" + Encrypt);
		PrintWriter out = response.getWriter();
		WXBizMsgCrypt wxcpt;
		try {
			wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
			String xml = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, Encrypt);
			System.out.println("Encryptjie:" + xml);
			// 解密xml成功，解析xml中相关数据
			if(xml.indexOf("Event")>0)
			{
				arr = xml.split("Event");
				Event=arr[1].toString();
				Event = rStr(Event);
                //场景0调用的条件
				if(Event.trim().equals("subscribe")&&xml.indexOf("FromUserName")>0)
				{
					arr = xml.split("FromUserName");
					FormUserName=arr[1].toString();
					FormUserName = rStr(FormUserName);
					InviteLog inviteLog =new InviteLog();
					inviteLog.setInviteUserId(FormUserName);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					inviteLog.setFollowTime(sdf.format(new Date()));
					inviteLog.setIffollow(1);
					this.inviteLogService.updateInvite(inviteLog);
					List<HongbaoSend> hbs= this.hongBaoSendService.selectHongBaoSend(FormUserName,sCorpID,"0");
					if(hbs.size()==0) {
						Random r = new Random();
						String money = String.valueOf(r.nextInt(101) + 100);

						sendHongbao(FormUserName, money,sCorpID,"0");
					}
				}
				//场景1调用的条件
			}
			log.info("FormUserName:" + FormUserName.toString() + "|   Event:" + Event);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public String rStr(String str){
		return str.replace("><![CDATA[","").replace("]]></", "");
	}
	//--------------------------------------------------------
//自定义菜单，我的红包
	public void sendHongbao(String userId,String money,String sCorpID,String type){
		Map<String, Object>map=new HashMap<String, Object>();
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=" + CacheUtils.getCachedAccessToken();
		String PostJson="{\"userid\":\""+userId+"\",\"agentid\":0}";
		String openjson= XYHttpUtils.doPost(url, PostJson);
		Open open= CommonUtils.gsonParseObject(openjson, Open.class);
		if(open.getAppid()!=null) {
			HongbaoSend hongBaoSend = new HongbaoSend();
			hongBaoSend.setUserId(userId);
			hongBaoSend.setCorpId(sCorpID);
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			hongBaoSend.setCreateTime(sdf1.format(new Date()));
			hongBaoSend.setMoney(money);
			hongBaoSend.setStatus("0");
			hongBaoSend.setErrormes("");
			hongBaoSend.setErrorcode("");
			hongBaoSend.setIfaccept("0");
			hongBaoSend.setIsdel("0");
			this.hongBaoSendService.addHongBaoSend(hongBaoSend);
			HongbaoUtils hb = new HongbaoUtils();
			hb.sendRedEnvelop(open.getOpenid(), open.getAppid(), money,sCorpID,type);
		}
		else{
			log.info("PostJson:" +PostJson);
		}

	}
	
}
